package com.hibase.core.excel.data;

import com.hibase.core.excel.context.AnalysisContext;
import com.google.common.collect.Lists;
import com.hibase.core.excel.enums.RowTypeEnum;
import com.hibase.core.excel.validator.ValidatorUtils;
import com.hibase.core.excel.vo.ErrorMessage;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * 默认数据分析处理器
 *
 * @author <a href="mailto:xiongliyi@hichain.com">Ian Xiong</a>
 * @since 1.4.35-V2
 */
@Slf4j
public class DefaultAnalysisProcessor extends ReadAnalysisProcessor<Object> {

    private Integer readRowIndex = 1;
    private final List<Object> data = Lists.newArrayList();
    private final List<ErrorMessage> errors = Lists.newArrayList();


    @Override
    public void invoke(Object rowEntity, AnalysisContext analysisContext) {
        if (RowTypeEnum.EMPTY.equals(analysisContext.readRowHolder().getRowType())) {
            log.debug("Empty row!");
            if (analysisContext.readWorkbookHolder().getIgnoreEmptyRow()) {
                return;
            }
        }
        readRowIndex++;

        Map<String, String> violations = ValidatorUtils.validateEntity(rowEntity);
        if (!violations.isEmpty()) {
            errors.add(new ErrorMessage(readRowIndex, violations));
        } else {
            data.add(rowEntity);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.debug("Reading excel is complete");
    }


    @Override
    public List<Object> getData() {
        return data;
    }

    @Override
    public List<ErrorMessage> getErrors() {
        return errors;
    }
}
